package apps.softtech.fastmarket;

import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import apps.softtech.Utility.ApplicationConstants;
import apps.softtech.Utility.HttpRequest;
import apps.softtech.fastmarket.adapter.AdapterChat;
import apps.softtech.fastmarket.adapter.AdapterListChat;
import apps.softtech.fastmarket.model.ChatLog;
import apps.softtech.fastmarket.model.DatabaseHandler;

@SuppressLint("SimpleDateFormat")
public class ServiceShowChatHead extends Service {
	/**
	 * Reference to the window
	 */
	private WindowManager mWindowManager;
	/**
	 * button chat
	 */
	private Button btChat;
	/**
	 * button close
	 */
	private Button btClose;
	/**
	 * layout chat
	 */
	private RelativeLayout layoutChat;
	/**
	 * layout list chat
	 */
	private LinearLayout layoutListChat;
	/**
	 * moving button chat
	 */
	boolean isMoving = false;
	/**
	 * move
	 */
	int mMove = 0;
	/**
	 * no move
	 */
	int mStand = 0;
	/**
	 * check layout chat
	 */
	boolean isChat = false;
	/**
	 * check close
	 */
	boolean isclose = false;
	/**
	 * params
	 */
	Context mContext;
	ServiceShowChatHead mActivity;
	WindowManager.LayoutParams params, paramsChat, paramsClose, paramsNew;
	/**
	 * get id chat
	 */
	int idUserChat;;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	/**
	 * Users chat
	 */
	Dialog dialogChat;
	/**
	 * List users chat
	 */
	ArrayList<ChatLog> mChatLogsArrayList = new ArrayList<ChatLog>();
	/**
	 * show list user chat
	 */
	Dialog dialogListChat;
	/**
	 * list id user chat
	 */
	/**
	 * data handler
	 */
	DatabaseHandler dbh;

	@SuppressLint("ServiceCast")
	@Override
	public void onCreate() {
		super.onCreate();
		// register broadcast
		registerReceiver(mBroadcastReceiver, new IntentFilter(
				ApplicationConstants.RECEIVER_SMS));
		mContext = this;
		mActivity = this;
		dbh = new DatabaseHandler(mContext);
		//
		// get list to chat
		//
		mChat_Lists_Id_User = (ArrayList<ChatLog>) dbh
				.getChatLog(true, new String[] { ChatLog.FROM_USER_ID,
						ChatLog.TO_USER_ID }, ChatLog.TO_USER_ID + " =? and "
						+ ChatLog.FROM_USER_ID + " !=?", new String[] {
						"" + ApplicationConstants.MY_USER,
						"" + ApplicationConstants.MY_USER },
						ChatLog.CHAT_LOG_ID + " DESC", null);

		mChatLogsArrayList = (ArrayList<ChatLog>) dbh.getChatLog(null, null,
				null, null, null);
		// init param
		createParam();
		// init width and height
		mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
		//
		// init
		//
		/**
		 * button chat
		 */
		btChat = new Button(this);
		btChat.setBackgroundResource(R.drawable.circle_chat);

		/**
		 * button close
		 */
		btClose = new Button(this);
		btClose.setBackgroundResource(R.drawable.ic_launcher);
		/**
		 * layout chat
		 */
		layoutChat = (RelativeLayout) LayoutInflater.from(
				ServiceShowChatHead.this).inflate(R.layout.activity_chat_out, null);
		layoutListChat = (LinearLayout) LayoutInflater.from(
				ServiceShowChatHead.this).inflate(R.layout.activity_chat_out_list,
				null);
		// create dialog chat
		createDialogChat();
		// init component layout chat
		initLayoutChat();
		// addview
		mWindowManager.addView(btChat, params);

		btChat.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				showAndCloseChat();

			}
		});
		btChat.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View arg0, MotionEvent event) {

				moveChat(event);
				return false;
			}

		});
	}

	/**
	 * Title list chat user
	 */
	TextView tvTitle;
	/**
	 * list view dialog list chat
	 */
	ListView lvListChatItem;
	/**
	 * adapter list id chat
	 */
	AdapterListChat mAdapterListChat;

	/**
	 * create dialog chat
	 */
	private void createDialogChat() {
		//
		// dialog to chat
		//
		dialogChat = new Dialog(ServiceShowChatHead.this);
		dialogChat.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialogChat.setCanceledOnTouchOutside(true);
		dialogChat.setContentView(layoutChat, paramsChat);
		WindowManager.LayoutParams wmlp = dialogChat.getWindow()
				.getAttributes();
		wmlp.gravity = Gravity.TOP | Gravity.LEFT;
		wmlp.x = 0;
		wmlp.y = 250;
		dialogChat.getWindow().setAttributes(wmlp);
		// adjustResize|stateHidden
		dialogChat.getWindow().setType(
				WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
		dialogChat.getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		dialogChat.getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		//
		// dialog list chat
		//
		dialogListChat = new Dialog(ServiceShowChatHead.this);
		dialogListChat.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialogListChat.setCanceledOnTouchOutside(true);
		dialogListChat.setContentView(layoutListChat, paramsChat);
		WindowManager.LayoutParams wmlp1 = dialogListChat.getWindow()
				.getAttributes();
		wmlp.gravity = Gravity.TOP | Gravity.LEFT;
		wmlp1.x = 0;
		wmlp1.y = 250;
		dialogListChat.getWindow().setAttributes(wmlp);
		dialogListChat.getWindow().setType(
				WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
		dialogListChat.getWindow().setBackgroundDrawableResource(R.drawable.border_layout);
		
		tvTitle = (TextView) layoutListChat.findViewById(R.id.tvTitleListChat);
		if (mChat_Lists_Id_User.size() == 0 || mChat_Lists_Id_User == null) {
			tvTitle.setText(getResources().getString(R.string.title_chat_no));
		}
		mAdapterListChat = new AdapterListChat(mChat_Lists_Id_User, mContext);
		lvListChatItem = (ListView) layoutListChat
				.findViewById(R.id.lvListChatItem);
		lvListChatItem.setAdapter(mAdapterListChat);
		lvListChatItem
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int position, long arg3) {
						idUserChat = mChat_Lists_Id_User.get(position)
								.getFromUserId();
						mChat_Lists.clear();
						for (int i = 0; i < mChatLogsArrayList.size(); i++) {
							if (idUserChat == mChatLogsArrayList.get(i)
									.getFromUserId()
									|| idUserChat == mChatLogsArrayList.get(i)
											.getToUserId()) {
								//
								// add data to list chat
								//
								ChatLog chatLog = new ChatLog();
								chatLog.setContent(mChatLogsArrayList.get(i)
										.getContent());
								chatLog.setCreatedDate(mChatLogsArrayList
										.get(i).getCreatedDate());
								chatLog.setFromUserId(mChatLogsArrayList.get(i)
										.getFromUserId());
								chatLog.setToUserId(mChatLogsArrayList.get(i)
										.getToUserId());
								chatLog.setType(mChatLogsArrayList.get(i)
										.getType());
								mChat_Lists.add(chatLog);
							}
						}
						mAdapterChat = new AdapterChat(mContext, mChat_Lists);
						lvListChat.setAdapter(mAdapterChat);
						lvListChat.setSelection(mChat_Lists.size() - 1);
						dialogListChat.dismiss();
						dialogChat.show();
					}
				});
	}

	/**
	 * button send
	 */
	Button btSendSms;
	/**
	 * edittext string sms
	 */
	EditText etSmsContent;

	/**
	 * init layout chat
	 */
	@SuppressWarnings("deprecation")
	private void initLayoutChat() {
		btSendSms = (Button) layoutChat.findViewById(R.id.btSendSms);
		etSmsContent = (EditText) layoutChat.findViewById(R.id.etSmsContent);

		btSendSms.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				mSmsContent = etSmsContent.getText().toString().trim();
				if (etSmsContent.getText().toString().trim().equals("")
						|| etSmsContent.getText().toString().trim()
								.equals(null)) {
					Log.v("content", " null");
				} else {
					// save database
					dbh.insertChatLog(new ChatLog(mSmsContent, toDay(),
							ApplicationConstants.MY_USER, idUserChat, 3));
					Log.v("save", "ok save");
					// my list
					if (mChat_Lists.size() == 0 || mChat_Lists == null) {
						mChat_Lists.add(new ChatLog(mSmsContent, toDay(),
								ApplicationConstants.MY_USER, idUserChat, 3));
						mAdapterChat = new AdapterChat(mContext, mChat_Lists);
						lvListChat.setAdapter(mAdapterChat);
					} else {
						mChat_Lists.add(new ChatLog(mSmsContent, toDay(),
								ApplicationConstants.MY_USER, idUserChat, 3));
						mAdapterChat.updateData(mChat_Lists);
					}
					lvListChat.setSelection(mChat_Lists.size() - 1);
					new AsystaskSendSms().execute();
				}
				etSmsContent.setText("");
			}
		});

		// init com.receiver.gcm.ok
		lvListChat = (ListView) layoutChat.findViewById(R.id.lvListChat);
		mSwipeRefreshLayout = (SwipeRefreshLayout) layoutChat
				.findViewById(R.id.swipe_container);
		//
		// set onclick
		//
		// swipeview
		mSwipeRefreshLayout.setColorScheme(android.R.color.holo_blue_dark,
				android.R.color.holo_blue_light,
				android.R.color.holo_green_light,
				android.R.color.holo_green_light);
		mSwipeRefreshLayout
				.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
					@Override
					public void onRefresh() {
						mSwipeRefreshLayout.setRefreshing(true);

						(new Handler()).postDelayed(new Runnable() {
							@Override
							public void run() {
								// adapter = new
								// AdapterSwipe(getApplicationContext(), item);
								// lv.setAdapter(adapter);
								mSwipeRefreshLayout.setRefreshing(false);

							}
						}, 3000);
					}
				});
		mAdapterChat = new AdapterChat(mContext, mChat_Lists);
		lvListChat.setAdapter(mAdapterChat);

	}

	/**
	 * show and hide chat
	 */
	private void showAndCloseChat() {
		if (isMoving == false) {
			params.x = 20;
			params.y = 20;
			mWindowManager.updateViewLayout(btChat, params);
			dialogListChat.show();
			// dialogChat.show();
		}
	}

	/**
	 * coordinates X
	 */
	int initialX;
	/**
	 * coordinates Y
	 */
	int initialY;
	/**
	 * coordinates touch X
	 */
	float initialTouchX;
	/**
	 * coordinates touch Y
	 */
	float initialTouchY;

	/**
	 * move item
	 * 
	 * @param event
	 */
	private void moveChat(MotionEvent event) {
		DisplayMetrics metrics = getResources().getDisplayMetrics();
		int width = metrics.widthPixels;
		int height = metrics.heightPixels;
		
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:

			initialX = params.x;
			initialY = params.y;
			initialTouchX = event.getRawX();
			initialTouchY = event.getRawY();
			break;
		case MotionEvent.ACTION_UP:
			// close chat
			if (params.y > (height - 300) && params.x < (width / 2 + 40)
					&& params.x > (width / 2 - 100)) {
				mWindowManager.removeView(btChat);
			}
			// don't move
			if (isclose) {
				mWindowManager.removeView(btClose);
				isclose = false;
			}
			if (mStand != mMove) {
				mStand = 0;
				mMove = 0;
			} else {
				isMoving = false;
			}
			break;
		case MotionEvent.ACTION_MOVE:
			//
			// update position
			//
			params.x = initialX + (int) (event.getRawX() - initialTouchX);
			params.y = initialY + (int) (event.getRawY() - initialTouchY);
			if (params.x >= width) {
				params.x = width - 5;
			}
			if (params.x <= 0) {
				params.x = 5;
			}
			if (params.y >= height) {
				params.y = height - 5;
			}
			if (params.y <= 0) {
				params.y = 5;
			}
			mWindowManager.updateViewLayout(btChat, params);

			isMoving = true;
			mMove++;
			//
			// close layout chat
			//
			if (isChat) {
				mWindowManager.removeView(layoutChat);
				isChat = false;
			}
			//
			// close chat when move to X
			//
			if (isclose == false) {

				paramsClose.x = width / 2 - 60;
				paramsClose.y = height - 200;
				mWindowManager.addView(btClose, paramsClose);
				isclose = true;
			}
			break;
		}
	}

	@Override
	public void onDestroy() {
		if (mWindowManager != null) {
			mWindowManager.removeView(btChat);
			mWindowManager.removeView(layoutChat);
		}
		super.onDestroy();
	}

	/**
	 * create param for layout
	 */
	private void createParam() {
		DisplayMetrics metrics = getResources().getDisplayMetrics();
		int width = metrics.widthPixels;
		int height = metrics.heightPixels;
		// close
		paramsClose = new WindowManager.LayoutParams(
				WindowManager.LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
				WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
						| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
				PixelFormat.TRANSLUCENT);
		paramsClose.gravity = Gravity.TOP | Gravity.LEFT;

		// button to chat
		params = new WindowManager.LayoutParams(
				WindowManager.LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.TYPE_PHONE,
				WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
						| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
				PixelFormat.TRANSLUCENT);
		params.gravity = Gravity.TOP | Gravity.LEFT;
		params.x = 10;
		params.y = 20;
		// button new chat
		paramsNew = new WindowManager.LayoutParams(
				WindowManager.LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.TYPE_PHONE,
				WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
						| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
				PixelFormat.TRANSLUCENT);
		paramsNew.gravity = Gravity.TOP | Gravity.LEFT;
		// chat
		paramsChat = new WindowManager.LayoutParams(width, height - 250,
				WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
				WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
						| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,

				PixelFormat.TRANSLUCENT);
		paramsChat.gravity = Gravity.TOP | Gravity.LEFT;
		paramsChat.x = 20;
		paramsChat.y = 300;
	}

	/**
	 * 
	 */
	private void createNewChat() {
		paramsNew.x = params.x + 100;
		paramsNew.y = params.y;
		Button btNew = btChat;
		btNew.setBackgroundResource(R.drawable.ic_launcher);
		mWindowManager.addView(btNew, paramsNew);

	}

	/**
	 * listview
	 */
	ListView lvListChat;
	/**
	 * adapter list chat
	 */
	AdapterChat mAdapterChat;
	/**
	 * swipelayout
	 */
	SwipeRefreshLayout mSwipeRefreshLayout;
	/**
	 * content sms
	 */
	String mSmsContent;
	/**
	 * list dialog to chat
	 */
	ArrayList<ChatLog> mChat_Lists = new ArrayList<ChatLog>();
	/**
	 * list id user chat
	 */
	ArrayList<ChatLog> mChat_Lists_Id_User = new ArrayList<ChatLog>();

	/**
	 * Today
	 * 
	 * @return
	 */
	private String toDay() {
		Calendar c = Calendar.getInstance();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		String formattedDate = df.format(c.getTime());
		return formattedDate;
	}

	/**
	 * send sms
	 */
	class AsystaskSendSms extends AsyncTask<Void, Void, Void> {
		List<NameValuePair> mList;
		HttpRequest mHttpRequest;
		String url = "";

		@Override
		protected void onPreExecute() {
			mHttpRequest = new HttpRequest();
			mList = new ArrayList<NameValuePair>();
			url = ApplicationConstants.BASE_URL + "gcmusers/submit_chat";
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			Log.v("save", "request server");
			// Toast.makeText(ActivityChat.this, ""+Constants.REG_ID,
			// Toast.LENGTH_LONG).show();
			mList.add(new BasicNameValuePair("data", addDataJson().toString()));
			Log.v("", mList.toString());
			mHttpRequest.makeServiceCall(url, HttpRequest.POST, mList);
			return null;
		}
	}

	/**
	 * set bitmap
	 */
	private Bitmap setBimap() {
		try {
			String url = "https://lh5.googleusercontent.com/-wocjYPvyASc/T3_mBi3-jrI/AAAAAAAAAEg/U7RYJu-I3N0/w385-h384-no/vemat9.jpg";
			Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(
					url).openConnection().getInputStream());
			return bitmap;
		} catch (Exception e) {
		}
		return null;
	}

	/**
	 * add data to send server
	 */
	private JSONObject addDataJson() {
		JSONObject mJsonObject = new JSONObject();
		try {
			mJsonObject.put("st_GcmId", ApplicationConstants.RED_ID);
			mJsonObject.put("st_ToUserId", idUserChat);
			mJsonObject.put("message", mSmsContent);
		} catch (Exception e) {
		}
		return mJsonObject;
	}

	BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			Bundle exBundle = intent.getExtras();
			String data = exBundle.getString("data");
			int idFromUser = exBundle.getInt("idfromuser");
			int toUserId = exBundle.getInt("idtouser");
			if (dialogChat.isShowing()) {
				if (mChat_Lists.size() == 0 || mChat_Lists == null) {
					mChat_Lists.add(new ChatLog(data, toDay(), idFromUser,
							toUserId, 3));
					mAdapterChat = new AdapterChat(mContext, mChat_Lists);
					lvListChat.setAdapter(mAdapterChat);
				} else {
					mChat_Lists.add(new ChatLog(data, toDay(), idFromUser,
							toUserId, 3));
					mAdapterChat.updateData(mChat_Lists);
				}
			}
			if (dialogListChat.isShowing()) {
				if (idFromUser != idUserChat) {
					ChatLog chatLog = new ChatLog();
					chatLog.setFromUserId(idFromUser);
					chatLog.setToUserId(ApplicationConstants.MY_USER);
					if (mChat_Lists_Id_User.size() == 0
							|| mChat_Lists_Id_User == null) {
						mChat_Lists_Id_User.add(chatLog);
						mAdapterListChat = new AdapterListChat(
								mChat_Lists_Id_User, mContext);
						lvListChatItem.setAdapter(mAdapterListChat);
					} else {
						mChat_Lists_Id_User.add(chatLog);
						mAdapterListChat.upDate(mChat_Lists_Id_User);//
					}
					lvListChatItem.setSelection(mChat_Lists_Id_User.size() - 1);
				}
			}
		}

	};

}
